package com.example.administrator.chinafood;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.util.Measure;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuWrapperFactory;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.chinafood.Adapter.MyListViewAdapter;
import com.example.administrator.chinafood.Adapter.TheFoodListView;
import com.example.administrator.chinafood.ToJsonResult.AllResult;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TheFood extends AppCompatActivity {

    private ListView list;
    private MyListViewAdapter<TheFoodListView> myAdapter = null;
    private List<TheFoodListView> mData1 = null;
    private TextView txt_title,txt_content,txt_cailiao,txt_tap;
    private ImageView img;
    private Context context;
    private int allnum = 0;
    private ArrayList<Bitmap> bit = new ArrayList<Bitmap>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thefood);

        context = this;

        list = (ListView)findViewById(R.id.thefood_listView);
        txt_title = (TextView)findViewById(R.id.thefood_name);
        txt_content = (TextView)findViewById(R.id.thefood_content);
        txt_cailiao = (TextView)findViewById(R.id.thefood_cailiao);
        txt_tap = (TextView)findViewById(R.id.thefood_tap);
        img = (ImageView)findViewById(R.id.thefood_img);
        init();
    }

    private OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    private String result = "";
    private void getData(){
        Intent intent = getIntent();
        String str = intent.getStringExtra("foodname");
        int num = 1;
        int start = 0;
        String values = "keyword="+str+"&num="+num+"&start="+start;
        final Request request = new Request.Builder()
                .header("Authorization","APPCODE ad5df328957c4ccea6e5087649649be1")
                .url("http://jisusrecipe.market.alicloudapi.com/recipe/search?"+values)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = new Message();
                msg.what = 0;
                myHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                result = response.body().string();
                Message msg = new Message();
                msg.what = 1;
                myHandler.sendMessage(msg);
            }
        });
    }
    private void getImg(String url){
         Request request = new Request.Builder()
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = new Message();
                msg.what = 0;
                myHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] img = response.body().bytes();
                Message msg = new Message();
                msg.what = 2;
                msg.obj = img;
                myHandler.sendMessage(msg);
            }
        });
    }

    private Handler myHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    Toast.makeText(context,"加载数据失败",Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    inData();
                    break;
                case 2:
                    byte [] theimg = (byte[])msg.obj;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(theimg,0,theimg.length);
                    img.setImageBitmap(bitmap);
                    break;
                case 3:
                    if (allnum == bit.size()){
                        inBuzhou();
                    }
                    break;
            }
        }
    };

    private void inData(){
        Gson gson = new Gson();
        AllResult allResult = gson.fromJson(result,AllResult.class);
        AllResult.theResult at = allResult.getResult();
        ArrayList<AllResult.ResultList> ar = at.getList();

        ArrayList<AllResult.Material> am = ar.get(0).getMaterial();
        String cailiao = "";
        for (AllResult.Material iam: am) {
            cailiao += iam.getMname() + ":" + iam.getAmount() + " ";
        }

        ArrayList<AllResult.Process> ap = ar.get(0).getProcess();

        txt_title.setText(ar.get(0).getName());
        txt_content.setText(ar.get(0).getContent());
        txt_tap.setText(ar.get(0).getTag());
        getImg(ar.get(0).getPic());
        txt_cailiao.setText(cailiao);

         allnum = ap.size();
        for (int i =0;i<ap.size();i++){
            getallImg(ap.get(i).getPic());
        }
    }

    private void inBuzhou(){
        Gson gson = new Gson();
        AllResult allResult = gson.fromJson(result,AllResult.class);
        AllResult.theResult at = allResult.getResult();
        ArrayList<AllResult.ResultList> ar = at.getList();
        ArrayList<AllResult.Process> ap = ar.get(0).getProcess();
        for (int i =0;i<ap.size();i++){
            mData1.add(new TheFoodListView(bit.get(i),ap.get(i).getPcontent()));
        }
        myAdapter.notifyDataSetChanged();
    }
    public void init(){
        mData1 = new ArrayList<TheFoodListView>();
        myAdapter = new MyListViewAdapter<TheFoodListView>((ArrayList)mData1,R.layout.adapter_listview_thefood) {
            @Override
            public void bindView(ViewHolder holder, TheFoodListView obj) {
                holder.setText(R.id.thefood_list_txt,obj.getContent());
                holder.setImageResource(R.id.thefood_list_img,obj.getImg());
            }
        };
        list.setAdapter(myAdapter);
        getData();
    }

    private void getallImg(String url){
        Request request = new Request.Builder()
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //bit.add( null );
                Message msg = new Message();
                msg.what = 3;
                myHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] img = response.body().bytes();
                bit.add( BitmapFactory.decodeByteArray(img,0,img.length) );
                Message msg = new Message();
                msg.what = 3;
                msg.obj = img;
                myHandler.sendMessage(msg);
            }
        });
    }

}
